package com.example.easyexcel.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.example.easyexcel.dao.AssetTargetInfoMapper;
import com.example.easyexcel.dto.AssetTargetInfo;
import com.example.easyexcel.listener.AssetTargetInfoSingleThreadListener;
import com.example.easyexcel.service.AssettargetInfoSingleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;

@Service
@RequiredArgsConstructor
@Slf4j
public class AssetTargetInfoSingleThreadServiceImpl implements AssettargetInfoSingleService {

    private final AssetTargetInfoMapper assetTargetInfoMapper;

    @Override
    public void importTargetExcel(MultipartFile file) {
        long totalStartTime = System.currentTimeMillis();
        Path tempFile = null;

        try {
            log.info("开始导入Excel文件: {}, 预计有多个sheet", file.getOriginalFilename());

            // 创建临时文件
            tempFile = Files.createTempFile("excel-import-", ".xlsx");
            file.transferTo(tempFile);
            log.info("临时文件创建成功");

            // 获取sheet总数
            int sheetCount = getSheetCount(tempFile.toString());
            log.info("检测到Excel共有 {} 个sheet", sheetCount);

            // 按顺序处理所有sheet
            processAllSheetsSequentially(tempFile.toString(), sheetCount);

            long totalElapsedTime = System.currentTimeMillis() - totalStartTime;
            log.info("所有sheet导入完成! 总耗时: {} 毫秒", totalElapsedTime);

        } catch (Exception e) {
            long totalElapsedTime = System.currentTimeMillis() - totalStartTime;
            log.error("Excel导入失败，已耗时: {} 毫秒", totalElapsedTime, e);
            throw new RuntimeException("Excel导入失败: " + e.getMessage(), e);
        } finally {
            // 清理临时文件
            if (tempFile != null) {
                try {
                    Files.deleteIfExists(tempFile);
                    log.debug("临时文件已清理");
                } catch (Exception e) {
                    log.warn("删除临时文件失败: {}", e.getMessage());
                }
            }
        }
    }

    /**
     * 获取Excel中的sheet数量
     */
    private int getSheetCount(String filePath) {
        try (ExcelReader excelReader = EasyExcel.read(filePath).build()) {
            return excelReader.excelExecutor().sheetList().size();
        } catch (Exception e) {
            log.warn("获取sheet数量失败，默认使用1个sheet: {}", e.getMessage());
            return 1;
        }
    }

    /**
     * 顺序处理所有sheet（单线程）
     */
    private void processAllSheetsSequentially(String filePath, int sheetCount) {
        long totalStartTime = System.currentTimeMillis();
        int totalProcessed = 0;
        int totalFailed = 0;

        for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) {
            long sheetStartTime = System.currentTimeMillis();

            try {
                log.info("开始处理第 {} 个sheet", sheetIndex + 1);

                // 为每个sheet创建独立的监听器实例
                AssetTargetInfoSingleThreadListener listener =
                        new AssetTargetInfoSingleThreadListener(assetTargetInfoMapper);

                // 读取指定sheet
                EasyExcel.read(filePath, AssetTargetInfo.class, listener)
                        .sheet(sheetIndex)
                        .doRead();

                long sheetTime = System.currentTimeMillis() - sheetStartTime;
                log.info("第 {} 个sheet处理完成, 耗时: {} 毫秒",
                        sheetIndex + 1, sheetTime);

            } catch (Exception e) {
                long sheetTime = System.currentTimeMillis() - sheetStartTime;
                log.error("第 {} 个sheet处理失败, 已耗时: {} 毫秒",
                        sheetIndex + 1, sheetTime, e);
                totalFailed++;
            }
        }

        long totalTime = System.currentTimeMillis() - totalStartTime;
        log.info("所有sheet处理完毕! 成功: {} 个, 失败: {} 个, 总耗时: {} 毫秒",
                sheetCount - totalFailed, totalFailed, totalTime);
    }
}